/**
 * Created by Administrator on 2017/5/25.
 */
var async = require('async');
var DBFactory = require('../db/mysql_db');
var Log = require('../dao/log.js');
var CONSTANT = require('../util/constant.js');
var UserAgentDao = require('../dao/user_agent');
var globalVar = require('../global_var');
var XingetApp = require('../XingetApp');
var Config = require('../config');
var UserDao = module.exports;


UserDao.login = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        //验证用户登录
        DBFactory.poolQuery('select * from users where account = ? ', [data.account],
            function () {
                cb("no connection");
            }, function (err, result) {
                if (err) {
                    cb(err);
                    console.log(err);
                    return;
                }
                if (result[0]) {
                    if (result[0]['password'] == data.password) {
                        if (result[0]['status'] == 0) {
                            cb('该账号已被停用，有问题请联系管理员');
                        } else {
                            cb(null, result[0]);
                        }
                    } else {
                        cb('密码或账号不正确');
                    }
                } else {
                    cb('不存在此用户');
                }
            });
    }
}

UserDao.loginAll = function (userInfo, cb) {
    if (!userInfo) {
        cb(new Error(500));
        return;
    }

    var applist = [];
    DBFactory.getConnection(function (error, connection) {//使用transaction创建新用户
        if (error) {
            cb(error);
        } else {
            async.waterfall([
                    // 开始Transaction
                    function (callback) {
                        connection.beginTransaction(function (err) {
                            callback(err);
                        });
                    },
                    function (callback) {
                        connection.query('select * from users where account = ? ', [userInfo.account],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result[0]) {
                                    if (!userInfo.thirdLogin) {
                                        if (result[0]['password'] != userInfo.password) {
                                            callback('密码或账号不正确', result[0].uid, null);
                                            return;
                                        }
                                    }
                                    if (result[0]['status'] == 0) {
                                        callback('该账号已被停用，有问题请联系管理员');
                                        return;
                                    }
                                    callback(null, result[0]);
                                } else {
                                    callback('不存在此用户');
                                }
                            });
                    },
                    function (user, callback) {
                        userInfo.uid = user.uid;
                        userInfo.name = user.name;
                        userInfo.account = user.account;
                        var userKeys = ['age','id_card','wx_account','qq','wx_unionid','ali_account','wx_avatar','wx_nick'];
                        userKeys.forEach(function (key) {
                            userInfo[key] = user[key] == null ? "" : user[key];
                        });
                        userInfo.recommendCode = uidToCode(user.uid);
                        userInfo.money = 0;
                        userInfo.real_name = user.real_name;
                        userInfo.secret_pwd = user.secret_pwd ? true : false;
                        userInfo.appInfo = [];


                        //有推荐人
                        UserDao.hasRecommender(userInfo.uid, function (e, result) {
                            if (e) {
                                callback(e);
                            } else {
                                for (var i = 0; i < result.length; i++) {
                                    var recommender = result[i].recommender;
                                    var app_sid = result[i].app_sid;
                                    if (!userInfo.app_sid) userInfo.money += result[i].money;
                                    if (userInfo.app_sid && userInfo.app_sid == app_sid) userInfo.money = result[i].money;
                                    if (applist.indexOf(app_sid) < 0) {
                                        if (userInfo.app_sid && app_sid != userInfo.app_sid) {
                                        } else {
                                            applist.push(app_sid);
                                            var hasRecommender = 0;
                                            if (recommender) {
                                                hasRecommender = 1;
                                            }
                                            if (userInfo.app_sid) {
                                                if (result[i].status == 0) {
                                                    var err = {};
                                                    err.status = '已被禁用';
                                                    err.comment = result[i].comment;
                                                    callback(err);
                                                    return;
                                                }
                                            }
                                            var applists = {
                                                app_sid: app_sid,
                                                reg_time: simpleDateFormat(result[i].created_time),
                                                app_name: result[i].name,
                                                hasRecommender: hasRecommender,
                                                group_name: result[i].group_name,
                                                status: result[i].status,
                                                comment: result[i].comment,
                                                pre_agent_lvl: result[i].pre_agent_lvl,
                                                agent_2:result[i].agent_2
                                            }
                                            userInfo.appInfo.push(applists);
                                        }
                                    }
                                }
                                callback(null, userInfo);
                            }
                        });
                    },
                    function (userInfo, callback) {
                        //查用户是否有使用过该app，没有就新增user_agent记录
                        if (applist.length == 0 && userInfo.app_sid) {
                            UserDao.addAgent(userInfo, function (e, data) {
                                if (e) {
                                    console.log(e);
                                    callback(e);
                                    return;
                                }
                                if (data) {
                                    var applists = {
                                        app_sid: userInfo.app_sid,
                                        app_name: data.name,
                                        hasRecommender: 0,
                                        agent_2:userInfo.agent_2
                                    }
                                    userInfo.isNewRigsterApp = true;
                                    userInfo.appInfo.push(applists);
                                    userInfo.server_time = simpleDateFormat(new Date());
                                }
                                callback(null, userInfo);
                            });
                        } else {
                            //有的话，就获取他的app所属的vip信息
                            UserDao.getVipInfo(userInfo, function (e, data) {
                                if (e) {
                                    callback(e);
                                } else {
                                    //现在没有试用期了
                                    // loginInfo.probation = probation(data.created_time);
                                    if (data) {
                                        for (var i = 0; i < userInfo.appInfo.length; i++) {
                                            var ob = [];
                                            var viplists = {};
                                            for (var j = 0; j < data.length; j++) {
                                                if (data[j].app_sid == applist[i]) {
                                                    userInfo.isEndTime = vipEndTime(data[j].end_time);
                                                    if (userInfo.isEndTime.can_use == 1) {
                                                        // userInfo.recommendCode = uidToCode(userInfo.uid);
                                                    }
                                                    userInfo.isEndTime.vip_end_time = simpleDateFormat(userInfo.isEndTime.vip_end_time);
                                                    var vipInfo = {
                                                        vip_sid: data[j].vip_sid,
                                                        vip_name: data[j].name,
                                                        created_time: simpleDateFormat(data[j].created_time),
                                                        end_time: userInfo.isEndTime.vip_end_time,
                                                        vip_level: data[j].lvl,
                                                        vip_type: data[j].vip_type,
                                                        can_use: userInfo.isEndTime.can_use
                                                    }
                                                    ob.push(vipInfo);
                                                    delete userInfo.isEndTime;
                                                }
                                            }
                                            ob.forEach(function (o) {
                                                viplists[o.vip_sid] = o;
                                            });
                                            userInfo.appInfo[i].vipInfo = viplists;
                                        }
                                    }
                                    userInfo.server_time = simpleDateFormat(new Date());
                                    callback(null, userInfo);
                                }
                            });
                        }
                    },
                    function (userInfo, callback) {
                        if (userInfo.app_sid) {
                            connection.query('select sid from app_vip where app_sid = ? and sid = "multiLogin"', [userInfo.app_sid],
                                function (err, result) {
                                    if (err) {
                                        callback(err);
                                        console.log(err);
                                        return;
                                    }
                                    if (result && result.length > 0) {
                                        userInfo.multiLogin = 1;
                                        callback(null, userInfo);
                                    } else {
                                        callback(null, userInfo);
                                    }
                                }
                            );
                        } else {
                            callback(null, userInfo);
                        }
                    }
                ],
                function (DbErr, Info) {
                    if (DbErr) {
                        connection.rollback(function () {
                            connection.release();
                            cb(DbErr);
                        });
                    } else {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, Info);
                            }
                        });
                    }
                }
            );
        }
    });
}

UserDao.wxlogin = function (par, cb) {
    if (!par) return cb(new Error(500));
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            return cb(error);
        }
        // 验证用户登录
        connection.query('select * from users where wx_unionid = ?', [par.wx_unionid],
            function (err, result) {
                connection.release();
                if (err) {
                    console.log(err);
                    return cb(err);
                }
                if (!result || !result[0] || !result[0].uid) return cb(null, {isVisitor: true});
                if (result[0].status == 0) return cb('该账号已被停用，有问题请联系管理员');

                var user = result[0];
                user.thirdLogin = 'wx';//不需要密码
                user.app_sid = par.app_sid;
                user.isNewRigsterApp = par.isNewRigsterApp;
                UserDao.loginAll(user, function (err, r) {
                    if (err) {
                        user.detail = err;
                        user.uid = r;
                        user.type = 4;//用户登陆失败
                        Log.userLog(user, function (result) {
                            cb(err);
                            return;
                        });
                        return;
                    }
                    delete user.password;
                    delete user.status;
                    delete user.created_date;
                    delete user.updated_date;
                    cb(null, user);
                });
            });
    });
}

// UserDao.wxlogin = function (par, cb) {
//     if (!par) return cb(new Error(500));
//     DBFactory.getConnection(function (error, connection) {
//         if (error) {
//             cb(error);
//         } else {
//             async.waterfall([
//                     function (callback) {
//                         // 验证用户登录
//                         connection.query('select * from users where wx_unionid = ?', [par.wx_unionid],
//                             function (err, result) {
//                                 if (err) {
//                                     callback(err);
//                                     console.log(err);
//                                     return;
//                                 }
//                                 if (result && result[0]) {
//                                     if (result[0]['status'] == 0) {
//                                         callback('该账号已被停用，有问题请联系管理员');
//                                     } else {
//                                         callback(null, result[0]);
//                                     }
//                                 } else {
//                                     callback(null, {isVisitor: true});
//                                 }
//                             });
//                     },
//                     function (user, callback) {
//                         if(user.isVisitor == true) return callback(null, user);
//                         user.thirdLogin = 'wx';//不需要密码
//                         user.app_sid = par.app_sid;
//                         UserDao.loginAll(user, function (err, r) {
//                             if (err) {
//                                 user.detail = err;
//                                 user.uid = r;
//                                 user.type = 4;//用户登陆失败
//                                 Log.userLog(user, function (result) {
//                                     callback(err);
//                                     return;
//                                 });
//                             }
//                             delete user.password;
//                             delete user.status;
//                             delete user.created_date;
//                             delete user.updated_date;
//                             callback(null, user);
//                         });
//                     }
//                 ],
//                 function (DbErr, Info) {
//                     connection.release();
//                     if (DbErr) {
//                         cb(DbErr);
//                     } else {
//                         cb(null, Info);
//                     }
//                 }
//             );
//         }
//     });
// }

UserDao.getWxRec = function (data, cb) {
    if (!data) return cb(new Error(500));
    DBFactory.poolQuery(
        'select b.recommendUid from users a left join user_app_wx_rec b on a.wx_unionid = b.wx_unionid' +
        ' where a.uid = ? and b.app_sid = ? ',
        [data.uid, data.app_sid],
        function () {
            cb("no connection");
        }, function (err, result) {
            if (err) {
                cb(err);
                console.log(err);
                return;
            }
            if (result[0] && result[0].recommendUid) {
                cb(null, result[0].recommendUid);
            } else {
                cb('没有推荐人');
            }
        });
}

UserDao.setRecommender = function (data) {
    console.log(data);
    UserDao.updateRecommender(data, function (err, result) {
        if (err) {
            console.log(err);
            return;
        }
        // console.log('设置推荐人成功！');
        console.log(result);
    });
}

UserDao.setWxRec = function (data, cb) {
    if (!data) return cb(new Error(500));
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
        } else {
            async.waterfall([
                    function (callback) {
                        canSetRec(data, callback);
                    },
                    function (canSet, callback) {
                        if (canSet) {
                            var sql = 'select b.recommendUid from users a left join user_app_wx_rec b on a.wx_unionid = b.wx_unionid' +
                                ' where a.uid = ? and b.app_sid = ? ';
                            connection.query(sql, [data.uid, data.app_sid], function (err, result) {
                                if (err) return callback(err);
                                if (result[0] && result[0].recommendUid) {
                                    data.recommendUid = result[0].recommendUid;
                                    setRecommender(data, callback);
                                } else {
                                    callback(null, '暂无推荐人')
                                }
                            })
                        } else {
                            callback(null, '设置推荐人成功！');
                        }
                    }
                ],
                function (DbErr, Info) {
                    connection.release();
                    if (DbErr) {
                        cb(DbErr);
                    } else {
                        cb(null, Info);
                    }
                }
            );
        }
    });
}

UserDao.vcodeLogin = function (data, cb) {
    if (!data) return cb(new Error(500));
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
        } else {
            async.waterfall([
                    function (callback) {
                        // 验证用户登录
                        connection.query('select * from users where account = ?', [data.account],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result && result[0]) {
                                    if (result[0]['status'] == 0) {
                                        callback('该账号已被停用，有问题请联系管理员');
                                    } else {
                                        callback(null, result[0]);
                                    }
                                } else {
                                    callback('还未注册该应用！');
                                }
                            });
                    },
                    function (user, callback) {
                        if (user.isVisitor == true) return callback(null, user);
                        user.thirdLogin = 'vcode';//不需要密码
                        user.app_sid = data.app_sid;
                        UserDao.loginAll(user, function (err, r) {
                            if (err) {
                                user.detail = err;
                                user.uid = r;
                                user.type = 4;//用户登陆失败
                                Log.userLog(user, function (result) {
                                    callback(err);
                                    return;
                                });
                            }
                            delete user.password;
                            delete user.status;
                            delete user.created_date;
                            delete user.updated_date;
                            callback(null, user);
                        });
                    }
                ],
                function (DbErr, Info) {
                    connection.release();
                    if (DbErr) {
                        cb(DbErr);
                    } else {
                        cb(null, Info);
                    }
                }
            );
        }
    });
}

/**
 * 获取微信推荐码
 */
UserDao.getWxRecCode = function (data, cb) {
    var sql = 'select recommendUid from user_app_wx_rec where app_sid = ? and wx_unionid = ? ';
    DBFactory.poolQuery(sql, [data.app_sid, data.wx_unionid],
        function () {
            cb("no connection");
        }, function (err, result) {
            if (err) {
                cb(err);
                console.log(err);
                return;
            }
            if (result[0] && result[0].recommendUid) {
                cb(null, result[0].recommendUid);
            } else {
                cb(null, 0);
            }
        });
}

/**
 * 微信绑定用户
 * @param data：uid、wx_unionid、app_sid
 */
function isExistUser(data, connection, callback) {
    var sql = ' select account, wx_unionid from users where account = ? or wx_unionid = ? ';
    connection.query(sql, [data.account, data.wx_unionid], function (err, result) {
        if (err) {
            callback(err);
        } else {
            if (result && result.length == 0) {
                UserDao.register(data, function (e) {
                    if (e) return callback(e);
                    data.isNewRigsterApp = true;
                    setWxunionid(data, connection, callback);
                });
            } else if (result && result[0] && result[0].account && !result[0].wx_unionid && result.length == 1) {
                setWxunionid(data, connection, callback);
            } else if (result && result[0] && result[0].account != data.account && result[0].wx_unionid && result.length == 1) {
                connection.release();
                callback('该微信号已被绑定！');
            } else {
                connection.release();
                callback('该手机号码已经绑定了微信号！');
            }
        }
    });
}

function setWxunionid(data, connection, callback) {
    var sql = 'update users set wx_unionid = ? where account = ? ';
    connection.query(sql, [data.wx_unionid, data.account], function (err, result) {
        if (err) {
            connection.release();
            callback(err);
        } else {
            connection.release();
            UserDao.wxlogin(data, callback);
        }
    });
}

UserDao.bindAccount = function (data, cb) {
    if (!data) return cb(new Error(500));
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
        } else {
            var sql = 'select uid, account from users where wx_unionid = ? and account = ?';
            connection.query(sql, [data.wx_unionid, data.account], function (err, result) {
                if (err) {
                    console.log(err);
                    cb(err);
                } else {
                    if (result && result.length > 0) {
                        UserDao.wxlogin(data, cb);
                        connection.release();
                    } else {
                        isExistUser(data, connection, cb);
                    }
                }
            });
        }
    });
}

/**
 * 用户绑定微信
 * @param data：uid、wx_unionid、app_sid
 */
// 查该传入的wx_unionid是否已被绑定
function isBindWX(data, connection, callback) {
    var sql = 'select count(*) as count, wx_unionid from users where uid = ? or wx_unionid = ? ';
    connection.query(sql, [data.uid, data.wx_unionid], function (err, result) {
        if (err) {
            console.log(err);
            return callback(err);
        }
        if (result && result[0].count == 1 && result[0].wx_unionid == data.wx_unionid) {
            callback(null, true);
        } else if (result && result[0].count == 2) {
            callback('该微信号已被绑定');
        } else if (result && result[0].count == 1 && !result[0].wx_unionid) {
            callback(null, false);
        } else if(result && result[0].count == 1 && result[0].wx_unionid != data.wx_unionid){
            callback('您的账号已绑定其他微信号，若要更换请联系客服处理');
        } else {
            callback('绑定时发生错误')
        }
    })
}

function bindWx(data, connection, callback) {
    var sql = 'update users set wx_unionid = ? where uid = ? ';
    connection.query(sql, [data.wx_unionid, data.uid], function (err, result) {
        if (err) {
            console.log(err);
            return callback(err);
        }
        if (result && result.affectedRows > 0) {
            canSetRec(data, function (e, r) {
                if (r) findWXRec(data, function () {
                });
            });
            callback(null, '绑定成功！');
        } else {
            callback('绑定是发生错误，请重试！');
        }
    });
}

function canSetRec(data, callback) {
    var sql = 'select recommender from user_app_new_agent where uid = ? and app_sid = ? ';
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            callback(error);
        } else {
            connection.query(sql, [data.uid, data.app_sid], function (err, result) {
                connection.release();
                if (err) {
                    console.log(err);
                    return callback(err);
                }
                if (result && result[0] && result[0].recommender) {
                    callback(null, false);
                } else {
                    callback(null, true);
                }
            });
        }
    });
}

function findWXRec(data, callback) {
    var sql = 'select * from user_app_wx_rec where app_sid = ? and wx_unionid = ? ';
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            callback(error);
        } else {
            connection.query(sql, [data.app_sid, data.wx_unionid], function (err, result) {
                connection.release();
                if (err) {
                    console.log(err);
                    return callback(err);
                }
                if (result && result[0] && result[0].recommendUid) {
                    data.recommendUid = result[0].recommendUid;
                    setRecommender(data, callback);
                } else {
                    callback(null, null);
                }
            });
        }
    });
}

function setRecommender(data, callback) {
    if (!data.recommendUid) return callback(null, true);
    //用户已注册该平台
    UserDao.updateRecommender(data, function (err, result) {
        if (err) {
            callback(err);
            return;
        }
        callback(null, '设置推荐人成功！');
    });
}

UserDao.bindWx = function (data, cb) {
    if (!data) return cb(new Error(500));
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
        } else {
            async.waterfall([
                    function (callback) {
                        // 查该传入的wx_unionid是否已被绑定
                        isBindWX(data, connection, callback);
                    },
                    function (isok, callback) {
                        //查看是否已经有推荐人了
                        if (isok) {
                            callback(null, '绑定成功！');
                        } else {
                            bindWx(data, connection, callback);
                        }
                    }
                ],
                function (DbErr, Info) {
                    connection.release();
                    if (DbErr) {
                        cb(DbErr);
                    } else {
                        cb(null, Info);
                    }
                });
        }
    });
}

/**
 * 判断是否注册平台  是否绑定微信  是否注册app  是否有推荐人
 * @param account  app_sid
 */
function isRegistPlatAndIsBindWx(data, connection, cb) {
    var sql = 'select uid, wx_unionid from users where account = ? ';
    connection.query(sql, [data.account], function (err, result) {
        if (err) {
            return cb(err);
        } else {
            var existInfo = {
                isRCExist:data.isRCExist
            };
            if (result.length == 0) {
                connection.release();
                existInfo.isRegPlat = false;
                existInfo.isBindWX = false;
                existInfo.isRegApp = false;
                existInfo.hasRec = false;
                cb(null, existInfo);
            } else {
                existInfo.isRegPlat = true;
                if (result[0] && !result[0].wx_unionid) {
                    existInfo.isBindWX = false;
                } else if (result[0] && result[0].wx_unionid) {
                    existInfo.isBindWX = true;
                }
                isRegistAppAndHasRec(existInfo, data, connection, cb);
            }
        }
    });
}

function isRegistAppAndHasRec(existInfo, data, connection, cb) {
    var sql = 'select recommender from user_app_new_agent where app_sid = ? and account = ? ';
    connection.query(sql, [data.app_sid, data.account], function (err, result) {
        if (err) {
            return cb(err);
        } else {
            if (result.length == 0) {
                connection.release();
                existInfo.isRegApp = false;
                existInfo.hasRec = false;
                cb(null, existInfo);
            } else {
                connection.release();
                existInfo.isRegApp = true;
                if (result[0] && result[0].recommender) {
                    existInfo.hasRec = true;
                } else {
                    existInfo.hasRec = false;
                }
                cb(null, existInfo);
            }
        }
    });
}

UserDao.existInfo = function (data, cb) {
    if (!data) return cb(new Error(500));
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        isRCExist(data,connection,function (err,result) {
            if (err) {
                cb(err);
                connection.release();
                return;
            }
            isRegistPlatAndIsBindWx(data, connection, cb);
        });
    });
};

//isRCExist 1:存在 2:不存在
function isRCExist(data,connection,cb) {
    if (!data.rc) {
        cb(null,{});
        return;
    }
    var findUid = codeToUid(data.rc);
    if (!findUid) {
        data.isRCExist = 2;
        cb(null,{});
        return;
    }
    var sql = 'SELECT * FROM user_app_new_agent WHERE uid = ? AND app_sid = ? ';
    var value = [findUid,data.app_sid];
    connection.query(sql, value, function (err, result) {
        if (err) {
            return cb(err);
        } else {
            data.isRCExist = result && result[0] ? 1 : 2;
            cb(null,{});
        }
    });
}

//子账号登陆主账号
UserDao.loginSub = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.getConnection(function (error, connection) {//使用transaction创建新用户
            if (error) {
                cb(error);
            } else {
                var subCount;
                async.waterfall([
                    // 开始Transaction
                    function (callback) {
                        connection.beginTransaction(function (err) {
                            callback(err);
                        });
                    },
                    //检查该主账号是否被拉黑
                    function (callback) {
                        connection.query("select status,comment from user_app_new_agent where uid = ? and app_sid = ? limit 1"
                            , [data.main_uid, data.app_sid]
                            , function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result && result[0]) {
                                    if (result[0].status == 0) {
                                        var err = {};
                                        err.status = '主账号已被禁用';
                                        err.comment = result[0].comment;
                                        callback(err);
                                        return;
                                    }
                                }
                                callback(null, true);
                            });
                    },
                    //检查是否是子账号登陆
                    function (isOK, callback) {
                        connection.query("select a.password,b.* from users a LEFT JOIN user_subaccount b on a.uid = b.sub_uid" +
                            " where a.account = ? and b.uid = ? and b.app_sid = ? limit 1"
                            , [data.account, data.main_uid, data.app_sid]
                            , function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result[0]) {
                                    if (result[0]['password'] == data.password) {
                                        if (result[0]['sub_status'] == 0) {
                                            callback('您已被主账号禁用');
                                            return;
                                        }
                                        if (result[0]['uid_status'] == 0) {
                                            callback('您已屏蔽该主账号');
                                            return;
                                        }
                                        callback(null, result[0]);

                                    } else {
                                        callback('密码或账号不正确');
                                    }
                                } else {
                                    callback('请确定是否在该平台有与主账号关联');
                                }
                            });
                    },
                    //获取主账号赋予子账号的权限
                    function (userInfo, callback) {
                        connection.query("select a.*,GROUP_CONCAT(c.sid) vip_sids " +
                            " from user_subaccount a LEFT JOIN app_vip c ON FIND_IN_SET(c.name,a.sub_auth) " +
                            "where a.sub_uid = ? and a.uid = ? and a.app_sid = ? limit 1", [userInfo.sub_uid, data.main_uid, data.app_sid],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    return;
                                }
                                if (result && result.length > 0) {
                                    result[0].uid = result[0].sub_uid;
                                    result[0].main_uid = data.main_uid;
                                    result[0].sub_name = result[0].sub_name;
                                    result[0].created_date = simpleDateFormat(result[0].created_date);
                                    result[0].qq = result[0].sub_qq;
                                    //不然后续token判断会失败
                                    if (result[0].sub_auth == '') {
                                        result[0].sub_auth = undefined;
                                    }
                                    result[0].account = data.account;
                                    delete result[0].sub_uid;
                                    delete result[0].sub_qq;
                                    // delete result[0].sub_name;
                                }
                                callback(null, result);
                            });
                    },
                    function (vipInfo, callback) {
                        if (!vipInfo) {
                            cb("该主账号没有赋予你权限");
                            return;
                        }
                        //权限是否过期
                        connection.query("SELECT a.lvl,a.vip_sid,a.vip_type,b.name,a.end_time FROM user_vip a LEFT JOIN app_vip b ON a.vip_sid = b.sid where FIND_IN_SET(a.vip_sid,?) and a.uid = ? and end_time > ? GROUP BY a.vip_sid", [vipInfo[0].vip_sids, data.main_uid, new Date()],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    return;
                                }
                                if (result.length > 0) {
                                    result.forEach(function (o) {
                                        o.end_time = simpleDateFormat(o.end_time);
                                    });
                                }
                                vipInfo[0].vipInfo = result;
                                callback(null, vipInfo);
                            });
                    },
                    function (vipInfo, callback) {
                        if (!vipInfo) {
                            callback("该主账号分配的权限已过期");
                            return;
                        }
                        connection.query("select uid,account,name,avatar FROM users where uid = ?", [data.main_uid],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    return;
                                }
                                vipInfo[0].main_userInfo = result[0];
                                callback(null, vipInfo);
                            });
                    },
                    function (vipInfo, callback) {
                        //搜索该用户在该app里的数值型权限（按数值判断是否能用）（信用积分和积分）
                        connection.query("select vip_sid,lvl,vip_type,name,a.end_time FROM user_vip a LEFT JOIN app_vip b ON a.app_sid = b.app_sid and a.vip_sid = b.sid where a.uid = ? and a.app_sid = ?", [data.main_uid, data.app_sid],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    return;
                                }
                                vipInfo[0].main_userInfo.vipInfo = [];
                                var subAuthEndTime;
                                if (result) {
                                    result.forEach(function (o) {
                                        o.end_time = simpleDateFormat(o.end_time);
                                        if (o.vip_sid == 'moneyPoint') {
                                            vipInfo[0].main_userInfo.vipInfo.push(o);
                                        }
                                        if (o.vip_sid == 'creditLvl') {
                                            vipInfo[0].main_userInfo.vipInfo.push(o);
                                        }
                                        if (o.vip_sid == 'subauth') {
                                            vipInfo[0].main_userInfo.vipInfo.push(o);
                                            subCount = o.lvl;
                                            subAuthEndTime = o.end_time;
                                        }
                                        if (o.vip_sid == 'publishGoods') {
                                            vipInfo[0].main_userInfo.vipInfo.push(o);
                                            subAuthEndTime = o.end_time;
                                        }
                                    })
                                }
                                if (subAuthEndTime < simpleDateFormat(new Date())) {
                                    callback('该主账号的子账号权限已过期');
                                    return;
                                }
                                callback(null, vipInfo[0]);
                            });
                    },
                    function (vipInfo, callback) {
                        //查看该主账号的子账号权限是否等级不够
                        connection.query("select COUNT(1) count from user_subaccount where uid = ? and app_sid = ?", [data.main_uid, data.app_sid],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    return;
                                }
                                if (result && result.length > 0) {
                                    if (result[0].count > subCount) {
                                        callback('该主账号的子账号权限等级不够，无法登陆');
                                        return;
                                    }
                                }
                                callback(null, vipInfo);
                            });
                    },
                    function (vipInfo, callback) {
                        connection.query("select sid from app_vip where app_sid = ? and sid = 'multiLogin'", [data.app_sid],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    return;
                                }
                                if (result && result.length > 0) {
                                    vipInfo.multiLogin = 1;
                                    callback(null, vipInfo);
                                } else {
                                    callback(null, vipInfo);
                                }
                            });
                    },
                ], function (DbErr, uidOrInfo) {
                    if (DbErr) {
                        connection.rollback(function () {
                            connection.release();
                            cb(DbErr);
                        });
                    } else {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, uidOrInfo);
                            }
                        });
                    }
                });
            }
        });
    }
}

UserDao.register = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.getConnection(function (error, connection) {//使用transaction创建新用户
            if (error) {
                cb(error);
            } else {
                async.waterfall([
                    // 开始Transaction
                    function (callback) {
                        connection.beginTransaction(function (err) {
                            callback(err);
                        });
                    },

                    //验证account
                    function (callback) {
                        connection.query("select * from users where account = ? limit 1", [data.account], function (err, result) {
                            var userOld = (result && result.length > 0) ? result[0] : undefined;
                            callback(err, userOld);
                        });
                    },

                    //插入/查询users表
                    function (userOld, callback) {
                        if (userOld) {//用户已注册
                            callback('用户已被注册！', false, null);
                        } else {//新用户
                            var user = {
                                status: 1,
                                account: data.account,
                                name: data.name,
                                password: data.password
                            };
                            //引流平台类型：ios/android/pc/web
                            if (data.source) {
                                user.reg_source = data.source;
                            }
                            if (data.qq) {
                                user.qq = data.qq;
                            }
                            //引流产品：benliu/huoma
                            user.reg_app = data.app_sid;
                            if (data.reg_plat) user.reg_plat = data.reg_plat; //合作平台
                            connection.query("insert into users set ?", user,
                                function (err, result) {
                                    var uid = (result) ? result.insertId : undefined;
                                    callback(err, uid);
                                });
                        }
                    },
                    function (uid, callback) {
                        if (uid) {
                            data.uid = uid;
                            data.detail = '注册成功！';
                            if (data.recommendCode) {
                                data.recommendUid = codeToUid(data.recommendCode);
                                UserDao.hasApp(data, function (error, result) {
                                    if (error) {
                                        console.log(error);
                                        data.recommendInfo = '推荐码不正确';
                                        delete data.recommendUid;
                                        callback(null, data);
                                        return;
                                    }
                                    delete data.recommendCode;
                                    if (!result) {
                                        // data.recommendInfo = '推荐人必须为vip用户或推荐码不正确！';
                                        data.recommendInfo = '推荐人必须已登陆该平台或推荐码不正确！';
                                        delete data.recommendUid;
                                        callback(null, data);
                                    } else {
                                        data.recommendInfo = '添加推荐人成功！';
                                        data.recommenderAccount = result.account;

                                        ['agent_1', 'agent_2', 'agent_3', 'agent_4', 'agent_5', 'agent_6'].forEach(
                                            function (t) {
                                                if (result[t]) data[t] = result[t];
                                            }
                                        );
                                        callback(null, data);
                                    }
                                });
                            } else {
                                callback(null, data);
                            }
                        }
                    },
                    function (data, callback) {
                        if (data) {
                            UserDao.addAgent(data, function (e, result) {
                                if (e) {
                                    data.detail += '，用户关联产品表失败!';
                                }
                                if (data.recommenderAccount) {
                                    pushToApp(data);
                                    delete data.recommenderAccount;
                                    UserAgentDao.addTeamNum(data);//设置推荐人成功后去增加团队人数，可以不成功，只是后台跑着
                                }
                                if (data.recommendUid) delete data.recommendUid;
                                ['agent_1', 'agent_2', 'agent_3', 'agent_4', 'agent_5', 'agent_6'].forEach(
                                    function (t) {
                                        delete data[t];
                                    }
                                );
                                callback(null, true, data);
                            });
                        }
                    }
                ], function (DbErr, isSuccess, uidOrInfo) {
                    if (DbErr) {
                        connection.rollback(function () {
                            connection.release();
                            cb(DbErr);
                        });
                    } else if (!isSuccess) {
                        connection.rollback(function () {
                            connection.release();
                            cb(DbErr);
                        });
                    } else {
                        connection.commit(function (e) {
                            if (e) {
                                connection.rollback(function () {
                                    connection.release();
                                    cb(e);
                                });
                            } else {
                                connection.release();
                                cb(null, uidOrInfo);
                            }
                        });
                    }
                });
            }
        });
    }
}

function pushToApp(data) {
    if (data.app_sid != 'usuz') return;
    var message = '您有新伙伴';
    if (data.account && data.account.length >= 11) message += '****' + data.account.substr(7, 4);
    message += '加入啦，快来看看吧！';
    data.plat = (data.agent_2 == Config.JNTB_ACCOUNT) ? 'jntb' : 'usuz';
    XingetApp.pushSimple2Account(data.plat, data.recommenderAccount, message, function (err, msg) {
        console.log(err + msg);
    });
}


UserDao.isVip = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.poolQuery('select count(uid) as count, max(lvl) lvl,account,uid from user_vip where uid = ? and app_sid =?', [data.recommendUid, data.app_sid],
            function () {
                cb("no connection")
            },
            function (err, result) {
                if (err) {
                    cb(err);
                    console.log(err);
                    return;
                }
                if (result[0].count) {
                    var flag = result[0].lvl ? true : false;
                    if (flag) {
                        cb(null, result[0]);
                    } else {
                        cb(null, false);
                    }
                } else {
                    cb(null, false);
                }
            });
    }
}

UserDao.hasApp = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.poolQuery('select * from user_app_new_agent where uid = ? and app_sid = ?', [data.recommendUid, data.app_sid],
            function () {
                cb("no connection")
            },
            function (err, result) {
                if (err) {
                    cb(err);
                    console.log(err);
                    return;
                }
                if (result && result.length == 1) {
                    cb(null, result[0]);
                } else {
                    cb(null, false);
                }
            });
    }
}

//recommenderAccount是上级账号，即b要设置a为他的上级，recommenderAccount是a
function hasSubAgent(data, recommenderAccount, cb) {
    if (data.app_sid == 'usuz') {

        // //先查是否是vip，vip的不能被设置为下线
        // DBFactory.poolQuery('select vip_sid as isVip from user_vip where account = ? and app_sid = ? GROUP BY account ', [data.account, data.app_sid],
        //     function () {
        //         cb("no connection")
        //     },
        //     function (err, result) {
        //         if (err) {
        //             cb(err);
        //             console.log(err);
        //             return;
        //         }
        //         if (result && result[0] && result[0].isVip) {
        //             cb('vip用户，无法设置');
        //         } else {
                    findIsTop(data.account, recommenderAccount, 0, data.app_sid, function (err) {
                        if (err) {
                            cb(err);
                            console.log(err);
                            return;
                        }
                        cb(null, null);
                    })
            //     }
            // });


    } else {
        DBFactory.poolQuery('select uid from user_app_new_agent where recommender = ? and app_sid = ?', [data.account, data.app_sid],
            function () {
                cb("no connection")
            },
            function (err, result) {
                if (err) {
                    cb(err);
                    console.log(err);
                    return;
                }
                if (result && result.length > 0) {
                    cb('已有团队，无法设置');
                } else {
                    cb(null, null);
                }
            });
    }
}

//查设置人recommenderAccount的上线，不能是被设置人account
//orignal_account 被设置人    account:当前被查的人，是设置人recommenderAccount的某层上级
function findIsTop(orignal_account, account, index, app_sid, cb) {

    if (index > 100) {
        cb('过渡循环，联系管理员');
        return;
    }

    if (orignal_account == account) {//被设置人 与 设置人或设置人的某个上级是同一个人
        cb('循环设置');
        return;
    }

    DBFactory.poolQuery('select recommender,pre_agent_lvl from user_app_new_agent where account = ? and app_sid = ?', [account, app_sid],
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb(err);
                console.log(err);
                return;
            }

            //设置人级设置人的上级
            if (!result || result.length <= 0 || !result[0].recommender) {//找不到上级了,最顶层的A
                if (account != orignal_account) {//设置人的最顶层人 不是 被设置人
                    cb(null, null);
                    return;
                } else {
                    cb('循环设置');
                    return;
                }
            }
            if (result[0].pre_agent_lvl > 0) {//查到的顶层人是代理的，可以直接设置
                cb(null, null);
                return;
            }
            //如果找到设置人上级，继续检查
            findIsTop(orignal_account, result[0].recommender, index + 1, app_sid, cb);
        });
}


function isFirstVip(data, cb) {
    DBFactory.poolQuery("select b.* from app_vip a left JOIN user_vip b on a.app_sid = b.app_sid and a.sid = b.vip_sid where a.sid = 'firstVip' and a.status = 1 and b.account = ? and a.app_sid = ?", [data.account, data.app_sid],
        function () {
            cb("no connection")
        },
        function (err, result) {
            if (err) {
                cb(err);
                console.log(err);
                return;
            }
            if (result && result.length > 0) {
                cb("该用户为首批特权用户，不能设置推荐人");
            } else {
                cb(null, null);
            }
        });
}

UserDao.addAgent = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.getConnection(function (error, connection) {
            if (error) {
                cb(error);
                return;
            }
            async.waterfall([
                    function (cb) {//先查是否存在该代理
                        connection.query("select * from apps where sid = ? limit 1", [data.app_sid], function (err, result) {
                            if (err) {
                                cb("没有该应用");
                                return;
                            }
                            if (result && result.length > 0) {
                                var appInfo = result[0];
                                cb(err, appInfo);
                            } else {
                                cb("没有该应用", null);
                                return;
                            }
                        });
                    },
                    function (appInfo, cb) {
                        if (!appInfo) return cb("没有该应用");

                        var sql = 'insert into user_app_exInfo set uid = ? , app_sid = ?, account = ? ';
                        connection.query(sql, [data.uid, data.app_sid, data.account],
                            function (error, result) {
                                if (error) {
                                    cb(error);
                                    // console.log(result);
                                    console.log(error);
                                    return;
                                }
                                if (result.affectedRows > 0) {
                                    cb(null, appInfo);
                                } else {
                                    cb("设置失败");
                                }
                            });

                    },
                    function (appInfo, cb) {
                        if (!appInfo) return cb("没有该应用");

                        var vipInfo = [];
                        var sql = 'insert into user_app_new_agent set recommender = ? , ' +
                            'recommender2 = (select a.recommender from (select recommender from user_app_new_agent where uid = ? and app_sid = ?) a ) , ' +
                            'uid = ? , app_sid = ? , ' +
                            'created_time = ? , account = ?, agent_1 = ?,agent_2 = ?,agent_3 = ?, agent_4 = ?,agent_5 = ?,agent_6 = ?,old_agent_6 = ?,old_recommender = ? ';
                        vipInfo.push(data.recommenderAccount);
                        vipInfo.push(data.recommendUid);
                        vipInfo.push(data.app_sid);
                        vipInfo.push(data.uid);
                        vipInfo.push(data.app_sid);
                        vipInfo.push(new Date());
                        vipInfo.push(data.account);

                        ['agent_1', 'agent_2', 'agent_3', 'agent_4', 'agent_5', 'agent_6',].forEach(
                            function (t) {
                                vipInfo.push(data[t]);
                            }
                        );
                        vipInfo.push(data.agent_6);
                        vipInfo.push(data.recommenderAccount);

                        connection.query(sql, vipInfo,
                            function (error, result) {
                                if (error) {
                                    cb(error);
                                    // console.log(result);
                                    console.log(error);
                                    return;
                                }
                                if (result.affectedRows > 0) {
                                    cb(null, appInfo);
                                } else {
                                    cb("设置失败");
                                }
                            });

                    }],
                function (err, res) {
                    connection.release();
                    if (err) {
                        cb(err);
                        return;
                    }
                    cb(null, res);
                });
        });

    }
}


UserDao.getUid = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.poolQuery('select uid from users where account = ?',
            [data],
            function () {
                cb("no connection");
            },
            function (err, result) {
                if (err) {
                    cb(err);
                    console.log(err);
                    return;
                }
                cb(null, result[0]);
            });
    }
}

UserDao.isPassword = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        //获取用户的密码
        DBFactory.poolQuery('select * from users where uid = ? ', [data.uid],
            function () {
                cb("no connection");
            },
            function (err, result) {
                if (err) {
                    cb(err);
                    console.log(err);
                    return;
                }
                if (result[0]) {
                    if (result[0].password == data.oldpassword) {
                        cb(null, result[0]);
                    } else {
                        cb('密码或账号不正确', result[0]);
                    }
                } else {
                    cb('不存在此用户');
                }
            });
    }
}
/**
 * 修改活动的操作者
 * @param data ：uid_own、sub_uid、new_sub_uid
 */
UserDao.changeAccount = function (data, cb) {
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
        } else {
            async.waterfall([
                function (callback) {
                    var sql2 = 'update user_app_agent set recommender3 = ? where recommender3 = ?';
                    connection.query(sql2, [data.newAccount, data.oldAccount],
                        function (err2, res2) {
                            if (err2) {
                                callback(err2);
                                return;
                            }
                            callback(null);
                        });
                },  // user_app_agent
                function (callback) {
                    var sql2 = 'update user_app_agent set recommender2 = ? where recommender2 = ?';
                    connection.query(sql2, [data.newAccount, data.oldAccount],
                        function (err2, res2) {
                            if (err2) {
                                callback(err2);
                                return;
                            }
                            callback(null);
                        });
                },
                function (callback) {
                    var sql2 = 'update user_app_agent set recommender = ? where recommender = ?';
                    connection.query(sql2, [data.newAccount, data.oldAccount],
                        function (err2, res2) {
                            if (err2) {
                                callback(err2);
                                return;
                            }
                            callback(null);
                        });
                },
                function (callback) {
                    var sql2 = 'update user_vip set account = ? where account = ? and uid = ?';
                    connection.query(sql2, [data.newAccount, data.oldAccount, data.uid],
                        function (err2, res2) {
                            if (err2) {
                                callback(err2);
                                return;
                            }
                            callback(null);
                        });
                },  // user_vip
                function (callback) {
                    var sql2 = 'update user_app_exInfo set account = ? where account = ?';
                    connection.query(sql2, [data.newAccount, data.oldAccount],
                        function (err2, res2) {
                            if (err2) {
                                callback(err2);
                                return;
                            }
                            callback(null);
                        });
                },  // user_app_exInfo
                function (callback) {
                    var sql2 = 'update sign_state set account = ? where account = ?';
                    connection.query(sql2, [data.newAccount, data.oldAccount],
                        function (err2, res2) {
                            if (err2) {
                                callback(err2);
                                return;
                            }
                            callback(null);
                        });
                },  // sign_state
                // function (callback) {
                //     var sql2 = 'update chat_record set account = ? where account = ?';
                //     connection.query(sql2, [data.newAccount, data.oldAccount],
                //         function (err2, res2) {
                //             if (err2) {
                //                 callback(err2);
                //                 return;
                //             }
                //             callback(null);
                //         });
                // },  // chat_record
                function (callback) {
                    var sql2 = 'update app_commission_new_ratio set account = ? where account = ?';
                    connection.query(sql2, [data.newAccount, data.oldAccount],
                        function (err2, res2) {
                            if (err2) {
                                callback(err2);
                                return;
                            }
                            callback(null);
                        });
                },  // app_commission_new_ratio
                function (callback) {
                    var sql2 = 'update app_commission_ratio set account = ? where account = ?';
                    connection.query(sql2, [data.newAccount, data.oldAccount],
                        function (err2, res2) {
                            if (err2) {
                                callback(err2);
                                return;
                            }
                            callback(null);
                        });
                },  // app_commission_ratio
                function (callback) {
                    var sql2 = 'update tao_acc_collection set account = ? where account = ?';
                    connection.query(sql2, [data.newAccount, data.oldAccount],
                        function (err2, res2) {
                            if (err2) {
                                callback(err2);
                                return;
                            }
                            callback(null);
                        });
                },  // tao_acc_collection
                function (callback) {
                    var sql2 = 'update user_cash set user_account = ? where user_account = ?';
                    connection.query(sql2, [data.newAccount, data.oldAccount],
                        function (err2, res2) {
                            if (err2) {
                                callback(err2);
                                return;
                            }
                            callback(null);
                        });
                },  // user_cash
                function (callback) {
                    var sql2 = 'update users set account = ? where account = ? and uid = ?';
                    connection.query(sql2, [data.newAccount, data.oldAccount, data.uid],
                        function (err2, res2) {
                            if (err2) {
                                callback(err2);
                                return;
                            }
                            callback(null);
                        });
                },  // users
            ], function (DbErr) {
                connection.release();
                if (DbErr) {
                    console.log(DbErr);
                    cb(DbErr);
                    return;
                }
                cb(null);
            });
        }
    });
}

UserDao.forgetPwd = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.poolQuery('update users set password = ? ,updated_date = CURRENT_TIMESTAMP where account = ?',
            [data.password, data.account],
            function () {
                cb("no connection");
            },
            function (err, result) {
                if (err) {
                    cb('找回密码失败！');
                    console.log(err);
                    return;
                }
                if (result.affectedRows == 0) {
                    cb('该账号未注册！');
                } else {
                    cb(null, result);
                }
            });
    }
}

UserDao.resetPwd = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.poolQuery('update users set password = ? ,updated_date = CURRENT_TIMESTAMP where uid = ?',
            [data.password, data.uid],
            function () {
                cb("no connection");
            },
            function (err, result) {
                if (err) {
                    cb('密码重置失败！');
                    console.log(err);
                    return;
                }
                else if (result) {
                    cb(null, result);
                }
            });
    }
}

UserDao.getVipInfo = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.poolQuery('select a.uid,a.vip_type,a.vip_sid, a.app_sid,a.created_time, a.lvl, a.end_time,b.name,b.top_lvl from user_vip a,app_vip b where account = ? and a.vip_sid = b.sid', [data.account],
            function () {
                cb("no connection");
            },
            function (e, result) {
                if (e) {
                    console.log(e);
                    cb('获取用户vip失败！');
                    return;

                }
                cb(null, result);
            });
    }
}

UserDao.showUserInfo = function (par, cb) {
    if (!par) {
        cb(new Error(500));
        return;
    }
    var userInfo = {};
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([
                function (callback) {
                    //获取用户基本信息
                    UserDao.getUserInfo(par, function (err, data) {
                        if (err) {
                            callback(err);
                            return;
                        }
                        if (data) {
                            userInfo.account = data.account;
                            userInfo.name = data.name;
                            userInfo.age = data.age == null ? "" : data.age;
                            userInfo.id_card = data.id_card == null ? "" : data.id_card;
                            userInfo.wx_account = data.wx_account == null ? "" : data.wx_account;
                            userInfo.ali_account = data.ali_account == null ? "" : data.ali_account;
                            userInfo.status = data.status;
                            userInfo.recommendCode = uidToCode(data.uid);
                            userInfo.money = 0;
                            userInfo.real_name = data.real_name;
                            userInfo.secret_pwd = data.secret_pwd ? true : false;
                        }
                        callback(null, userInfo);
                    });
                },
                function (userInfo, callback) {
                    //检查用户是否有使用该产品
                    if (par.app_sid) {
                        UserDao.isInApp(par, function (e, r) {
                            if (e) {
                                callback(e);
                                return;
                            }
                            if (r) {
                                userInfo.money = r.money;
                                callback(null, userInfo);
                                return;
                            }
                        })
                    } else {
                        callback(null, userInfo);
                    }
                },
                // function (userInfo, callback) {
                //     //获取用户vip信息
                //     UserDao.getVipInfo(userInfo, function (e, result) {
                //         if (e) {
                //             cb(e);
                //         } else {
                //             if (result) {
                //                 var applist = [];
                //                 for (var j = 0; j < result.length; j++) {
                //                     var app_sid = result[j].app_sid;
                //                     if (applist.indexOf(app_sid) < 0) {
                //                         if (par.app_sid && app_sid != par.app_sid) {
                //                         } else {
                //                             applist.push(app_sid);
                //                             userInfo.isEndTime = vipEndTime(result[j].end_time);
                //                             if (userInfo.isEndTime.can_use == 1) {
                //                                 // userInfo.recommendCode = uidToCode(userInfo.uid);
                //                             }
                //                         }
                //                     }
                //                 }
                //                 delete userInfo.isEndTime;
                //                 callback(null,userInfo);
                //             }
                //         }
                //     });
                // },
            ],
            function (err, userInfo) {
                connection.release();
                if (err) {
                    cb(err);
                } else {
                    cb(null, userInfo);
                }
            });
    })

}


/**
 * 用户设置推荐人
 * @param uid、account，recommenderUid
 * @param cb
 */
UserDao.updateRecommender = function (data, cb) {
    console.log(data);
    if (data.recommendUid) {
        //判断用户是否是首批特权用户
        isFirstVip(data, function (err) {
            if (err) return cb(err);
            //判断用户是否有推荐人
            UserDao.getRecommender(data, function (e, r) {
                    if (e) {
                        cb(e);
                        return;
                    }
                    if (r.recommender) {
                        cb("该用户已有推荐人");
                    } else {
                        //判断要设置的推荐人是否是vip用户
                        UserDao.hasApp(data, function (error, result) {
                            if (error) {
                                cb("推荐码不正确");
                                return;
                            }
                            if (!result) {
                                cb("推荐人必须已登录该平台或推荐码不正确！");
                                return;
                            } else {
                                hasSubAgent(data, result.account, function (err) {
                                    if (err) return cb(err);
                                    data.recommenderAccount = result.account;
                                    var agentInfo = [];
                                    var sql = 'update user_app_new_agent set recommender = ? , ' +
                                        'recommender2 = (select a.recommender from (select recommender from user_app_new_agent where uid = ? and app_sid = ?) a ) , ' +
                                        'agent_1 = ?, agent_2 = ?, agent_3 = ?, agent_4 = ?, agent_5 = ?, agent_6 = ?, old_agent_6 = ?, old_recommender = ? where uid = ? and app_sid = ?';
                                    agentInfo.push(data.recommenderAccount);
                                    agentInfo.push(data.recommendUid);
                                    agentInfo.push(data.app_sid);
                                    ['agent_1', 'agent_2', 'agent_3', 'agent_4', 'agent_5', 'agent_6',].forEach(
                                        function (t) {
                                            agentInfo.push(result[t]);
                                        }
                                    );
                                    agentInfo.push(result.agent_6);
                                    agentInfo.push(data.recommenderAccount);
                                    agentInfo.push(data.uid);
                                    agentInfo.push(data.app_sid);
                                    data.agent_2 = result.agent_2;
                                    DBFactory.poolQuery(sql, agentInfo,
                                        function () {
                                            cb("no connection");
                                        },
                                        function (err) {
                                            if (err) {
                                                cb("设置推荐人失败");
                                                return;
                                            }
                                            cb(null, "设置推荐人成功");
                                            UserAgentDao.addTeamNum(data);//设置推荐人成功后去增加团队人数，可以不成功，只是后台跑着
                                            UserAgentDao.addRealSub(data, 'all'); //设置推荐人的时候，如果有uuid且ali_user_id，则增加有效用户数
                                            pushToApp(data);
                                        });
                                });
                            }
                        });
                    }
                }
            )
        });
    }
}

//获取推荐人
UserDao.getRecommender = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {

        DBFactory.poolQuery('select recommender from user_app_new_agent where uid = ? and app_sid = ?',
            [data.uid, data.app_sid],
            function () {
                cb("no connection")
            },
            function (err, result) {
                if (err) {
                    console.log(data.uid);
                    cb(err);
                    return;
                }
                if (result && result[0]) {
                    cb(null, result[0]);
                } else {
                    console.log(data.app_sid);
                    cb("该用户没登过该应用");
                }
            });
    }
}

//查找是否有推荐人
UserDao.hasRecommender = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        DBFactory.poolQuery('select a.app_sid,a.recommender,b.name,a.created_time,a.status,a.comment,a.money,a.pre_agent_lvl,a.agent_2,GROUP_CONCAT(distinct c.group_name) group_name from user_app_new_agent a ' +
            'left join apps b on a.app_sid = b.sid LEFT JOIN user_subaccount c on a.uid = c.uid and a.app_sid = c.app_sid where a.uid = ? GROUP BY a.app_sid', [data],
            function () {
                cb("no connection")
            },
            function (e, r) {
                if (e) {
                    console.log(e);
                    cb('获取用户推荐人失败！');
                    return;
                }
                cb(null, r);
            });
    }
}

UserDao.usersInfoByTimeAndPhone = function (data, cb) {

    if (!data) {
        cb(new Error(500));
        return;
    }
    var sql;
    var sqlValue = {};
    if (data.account && data.startTime) {
        var startTime = data.startTime + ' 00:00:00';
        var endTime = data.endTime ? data.endTime + ' 23:59:59' : data.startTime + ' 23:59:59';
        if (data.phoneTail) {
            sql = 'select uid,account,name,status,age,sex,email from users where substring(account,-4) = ? and created_date >= ? and created_date <= ?';
        } else {
            sql = 'select uid,account,name,status,age,sex,email from users where account = ? and created_date >= ? and created_date <= ?';
        }
        sqlValue.value = [data.account, startTime, endTime];
    } else if (data.account) {
        if (data.phoneTail) {
            sql = 'select uid,account,name,status,age,sex,email from users where substring(account,-4) = ?';
        } else {
            sql = 'select uid,account,name,status,age,sex,email from users where account = ?';
        }
        sqlValue.value = data.account;
    } else if (data.startTime) {
        var startTime = data.startTime + ' 00:00:00';
        var endTime = data.endTime ? data.endTime + ' 23:59:59' : data.startTime + ' 23:59:59';
        sql = 'select uid,account,name,status,age,sex,email from users where created_date >= ? and created_date <= ?';
        sqlValue.value = [startTime, endTime];
    }
    if (data.app_sid) {
        sql += ' and app_sid = ?';
        sqlValue.value.push(app_sid);
    }

    console.log(sqlValue.value);
    DBFactory.poolQuery(sql, sqlValue.value,
        function () {
            cb("no connection")
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            var usersInfo = {};
            usersInfo.users = result;
            cb(null, usersInfo);
        }
    );

}


UserDao.updateUser = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }

    if (data.isAdmin == true) {

        DBFactory.getConnection(function (error, connection) {
            if (error) {
                cb(error);
                return;
            }
            async.waterfall([

                function (callback) {
                    connection.beginTransaction(function (err) {
                        callback(err);
                    });
                },

                function (callback) {//修改
                    connection.query('update users set ? where uid = ? ', [data.usersInfo, data.uid], function (err, result) {
                        if (err) {
                            callback(err);
                            return;
                        }
                        if (result.affectedRows > 0) {
                            callback(null, '继续');
                        } else {
                            callback('操作失败');
                            console.log('修改用户信息时，更改users表失败');
                        }
                    });
                },

                function (users, callback) {
                    if (!users) {
                        callback('操作失败', null);
                        console.log('修改用户信息时，更改users表失败');
                        return;
                    }
                    var adminLog = {
                        uid: data.uid,
                        adm_uid: data.adm_uid,
                        type: 4,
                        account: data.account,
                        detail: '管理员修改用户资料：'
                    };
                    //记录修改的参数
                    for (var p in data.usersInfo) {
                        adminLog.detail += p + ':' + data.usersInfo[p];
                    }
                    connection.query('insert into admin_log set ? ', adminLog, function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        if (result.affectedRows > 0) {
                            callback(null, '操作成功');
                        } else {
                            callback('操作失败', null);
                            console.log('操作admin_log表失败')
                        }
                    });

                }

            ], function (err, res) {
                if (err) {
                    connection.rollback(function () {
                        connection.release();
                        cb(err);
                    });
                } else {
                    connection.commit(function (e) {
                        if (e) {
                            connection.rollback(function () {
                                connection.release();
                                cb(e);
                            });
                        } else {
                            connection.release();
                            cb(null, res);
                        }
                    });
                }
            });

        });

    } else {
        for (var i in data) {
            console.log(i + ':' + data[i]);
        }
        DBFactory.poolQuery('update users set ? where uid = ?', [data.usersInfo, data.uid],
            function () {
                cb("no connection");
            },
            function (err, result) {
                if (err) {
                    console.log(err);
                    cb(err);
                    return;
                }
                if (result.affectedRows > 0) {
                    cb(null, '操作成功');
                    return;
                }
                cb('操作失败');
            }
        );
    }
}

UserDao.getUserInfo = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        var sql = data.account ? 'select * from users where account = ? ' :
            'select * from users where uid = ? ';
        var value = data.account ? [data.account] : [data.uid];
        //验证用户登录
        DBFactory.poolQuery(sql, value,
            function () {
                cb("no connection");
            }, function (err, result) {
                if (err) {
                    cb(err);
                    console.log(err);
                    return;
                }
                if (result[0]) {
                    cb(null, result[0]);
                } else {
                    cb('不存在此用户');
                }
            });
    }
}

UserDao.isInApp = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        //验证用户登录
        DBFactory.poolQuery('select * from user_app_new_agent where uid = ? and app_sid = ?', [data.uid, data.app_sid],
            function () {
                cb("no connection");
            }, function (err, result) {
                if (err) {
                    cb(err);
                    console.log(err);
                    return;
                }
                if (result[0]) {
                    cb(null, result[0]);
                } else {
                    cb('用户没有使用过该产品');
                }
            });
    }
}

//添加或更新子账号
UserDao.addorupdateSubAccount = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }
    var cf = globalVar.config[data.app_sid + '_onlySuper'];
    var onlySuper = (cf && cf.value == '1') ? true : false;
    //添加子账号
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },
            function (callback) {
                if (data.isUpdate == '0') {
                    //查看子账号权限
                    connection.query('select lvl FROM user_vip WHERE uid = ? and vip_sid = "subauth" and end_time > ? and app_sid = ?', [data.uid, new Date(), data.app_sid], function (err, result) {
                        if (err) {
                            callback(err);
                            return;
                        }
                        if (result.length > 0) {
                            connection.query('select COUNT(1) sub_num FROM user_subaccount WHERE uid = ? and app_sid = ?', [data.uid, data.app_sid], function (err, r) {
                                if (err) {
                                    callback(err);
                                    return;
                                }
                                if (r) {
                                    if (r[0].sub_num < result[0].lvl) {
                                        callback(null, true);
                                    } else {
                                        callback('子账号个数已满，请购买更高等级的子账号权限');
                                    }
                                } else {
                                    callback(null, true);
                                }
                            });
                        } else {
                            callback('该主账号没有子账号权限');
                        }
                    });
                } else {
                    callback(null, true);
                }
            },
            function (isOK, callback) {
                //取出子账号的uid
                connection.query('select * from users where account = ? limit 1', [data.sub_account], function (err, result) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    if (result && result[0]) {
                        //检查子账号是否被禁(暂不考虑)
                        // if(result[0].status == 0){
                        //     callback('该子账号用户已被管理员禁用');
                        // }else {
                        data.sub_uid = result[0].uid;
                        if (data.sub_uid == data.uid) {
                            callback('不能添加自己为子账号');
                            return;
                        }
                        callback(null, result[0]);
                    } else {
                        callback('不存在此子账号用户');
                    }
                });
            },
            function (users, callback) {
                var sql = 'select GROUP_CONCAT(uid) as uids from user_subaccount where sub_uid = ? and app_sid = ?';
                connection.query(sql, [data.sub_uid, data.app_sid], function (err, result) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    console.log(result);
                    if (result && result[0] && result[0].uids) {
                        var list = result[0].uids.split(',');
                        if (data.isUpdate == 0) {
                            if (list.length > 0) {
                                if (list.indexOf(''+data.uid) >= 0) {
                                    return callback('已添加该子账号，只能更新,不能重复添加');
                                } else if (onlySuper) {
                                    return callback('该子账号在该平台已经有主账号跟他关联');
                                } else {
                                    return callback(null, users);
                                }
                            } else {
                                return callback(null, users);
                            }
                        } else {
                            if (list.length >= 1 && list.indexOf(''+data.uid) >= 0) {
                                return callback(null, users);
                            } else {
                                return callback('请确定是否有关联该子账号');
                            }
                        }
                    } else if (data.isUpdate == 1) {
                        return callback('未找到关联该子账号的记录');
                    } else {
                        return callback(null, users);
                    }
                });
            },
            function (users, callback) {
                //判断昵称是否重复
                if (data.sub_name) {
                    connection.query('select * from user_subaccount where sub_name = ? and uid = ? and sub_uid != ?', [data.sub_name, data.uid, data.sub_uid], function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        if (result && result.length > 0) {
                            callback('已有该子账号昵称,请重取');
                        } else {
                            callback(null, true);
                        }
                    });
                } else {
                    callback(null, true);
                }
            },
            function (users, callback) {
                var toSet = {};
                catchSubAccountColumn(data, toSet, function (err, d) {
                    if (err) {
                        cb(err);
                        return;
                    }
                    if (data.isUpdate == 0) {
                        connection.query('insert into user_subaccount set ? ', toSet, function (err, result) {
                            if (err) {
                                callback(err, null);
                                return;
                            }
                            if (result.affectedRows > 0) {
                                callback(null, '操作成功');
                            } else {
                                callback('操作失败', null);
                            }
                        });
                    } else {
                        //主账号修改子账号信息
                        var sql = 'update user_subaccount set ? where uid = ?';
                        var sqlValue = [toSet, data.uid];
                        if (data.app_sid) {
                            sql += ' and app_sid = ?';
                            sqlValue.push(data.app_sid);
                        }
                        if (data.sub_uid) {
                            sql += ' and sub_uid = ?';
                            sqlValue.push(data.sub_uid);
                        }
                        connection.query(sql, sqlValue, function (err, result) {
                            if (err) {
                                callback(err, null);
                                return;
                            }
                            if (result.affectedRows > 0) {
                                callback(null, data.sub_uid);
                            } else {
                                callback('操作失败', null);
                            }
                        });
                    }
                });
            },

        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });
}

//更新子账号
UserDao.updateSubAccount = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }
    var cf = globalVar.config[data.app_sid + '_onlySuper'];
    var onlySuper = (cf && cf.value == '1') ? true : false;
    //添加子账号
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([
            function (callback) {
                var sql = 'select a.*,b.account as sub_account from user_subaccount a left join users b on a.sub_uid = b.uid where a.sub_uid = ? and a.app_sid = ? limit 1';
                connection.query(sql, [data.sub_uid, data.app_sid], function (err, result) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    if (!onlySuper) {
                        if (result && result[0]) {
                            data.sub_account = result[0].sub_account;
                        }
                        callback(null, true);
                        return;
                    } else {
                        if (result && result[0] && onlySuper && result[0].sub_uid && result[0].sub_status == 1 && result[0].uid != data.uid) {
                            callback('该子账号在该平台已经有主账号跟他关联');
                            return;
                        } else {
                            data.sub_account = result[0].sub_account;
                            callback(null, true);
                        }
                    }
                });
            },
            function (isok, callback) {
                //判断昵称是否重复
                if (data.sub_name) {
                    connection.query('select * from user_subaccount where sub_name = ? and uid = ?', [data.sub_name, data.uid], function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        if (result && result.length > 0) {
                            callback('已有该子账号昵称,请重取');
                        } else {
                            callback(null, true);
                        }
                    });
                } else {
                    callback(null, true);
                }
            },
            function (users, callback) {
                var toSet = {};
                catchSubAccountColumn(data, toSet, function (err, d) {
                    if (err) {
                        cb(err);
                        return;
                    }
                    //主账号修改子账号信息
                    var sql = 'update user_subaccount set ? where uid = ?';
                    var sqlValue = [toSet, data.uid];
                    if (data.app_sid) {
                        sql += ' and app_sid = ?';
                        sqlValue.push(data.app_sid);
                    }
                    if (data.sub_uid) {
                        sql += ' and sub_uid = ?';
                        sqlValue.push(data.sub_uid);
                    }
                    connection.query(sql, sqlValue, function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        if (result.affectedRows > 0) {
                            callback(null, data.sub_account);
                        } else {
                            callback('操作失败', null);
                        }
                    });
                });
            },
        ], function (err, res) {
            connection.release();
            if (err) {
                cb(err);
            } else {
                cb(null, res);
            }
        });

    });
}

function catchSubAccountColumn(data, toSet, cb) {

    if (data.uid) toSet.uid = data.uid;
    if (data.app_sid) toSet.app_sid = data.app_sid;
    if (data.sub_uid) toSet.sub_uid = data.sub_uid;
    if (data.sub_name) toSet.sub_name = data.sub_name;
    if (data.hasOwnProperty('sub_auth')) toSet.sub_auth = data.sub_auth;
    if (data.group_name) toSet.group_name = data.group_name;
    if (data.sub_qq) toSet.sub_qq = data.sub_qq;
    if (data.act_no) toSet.act_no = data.act_no;
    if (data.act_count) toSet.act_count = data.act_count;
    if (data.sub_wx) toSet.sub_wx = data.sub_wx;
    if (data.comment) toSet.comment = data.comment;
    cb(null, null);
}

/**
 * 修改状态(子账号或者是主账号状态)
 */
UserDao.setSubStatus = function (data, cb) {
    if (!data) {
        cb('请求参数不完整');
    } else {

        var cf = globalVar.config[data.app_sid + '_onlySuper'];
        var onlySuper = (cf && cf.value == '1') ? true : false;
        DBFactory.getConnection(function (error, connection) {
            if (error) {
                cb(error);
                return;
            }
            async.waterfall([
                    function (callback) {
                        if (onlySuper && onlySuper == '1' && data.sub_status == 1) {
                            var sql = 'select * from user_subaccount where sub_uid = ?';
                            var sqlValue = [];
                            sqlValue.push(data.sub_uid);
                            if (data.group_name) {
                                sql += ' and group_name = ?';
                                sqlValue.push(data.group_name);
                            }
                            connection.query(sql, sqlValue,
                                function (err, result) {
                                    if (err) {
                                        callback(err);
                                        console.log(err);
                                        return;
                                    }
                                    if (result && result[0]) {
                                        if (data.uid != result[0].uid && result[0].sub_status == 1) {
                                            callback('该子账号已经有和其他主账号关联');
                                            return;
                                        }
                                        callback(null, true);
                                    } else {
                                        callback('请确定是否与该子账号关联');
                                        return;
                                    }
                                });
                        } else {
                            callback(null, true);
                        }
                    },
                    function (isOK, callback) {
                        var sql = 'update user_subaccount';
                        var sqlValue = [];
                        if (data.sub_status) {
                            sql += ' set sub_status = ?';
                            sqlValue.push(data.sub_status);
                            if (data.sub_status == 0) {
                                sql += ',quit_date = ?';
                                sqlValue.push(new Date());
                            } else if (data.sub_status == 1) {
                                sql += ',quit_date = ?';
                                sqlValue.push(null);
                            }
                        }
                        if (data.uid_status) {
                            sql += ' set uid_status = ?';
                            sqlValue.push(data.uid_status);
                        }
                        sql += ' where uid = ? and app_sid = ? and sub_uid = ?';
                        sqlValue.push(data.uid);
                        sqlValue.push(data.app_sid);
                        sqlValue.push(data.sub_uid);
                        if (data.group_name) {
                            sql += ' and group_name = ?';
                            sqlValue.push(data.group_name);
                        }
                        connection.query(sql, sqlValue,
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result.affectedRows > 0) {
                                    callback(null, true);
                                } else {
                                    callback('操作失败');
                                }
                            });
                    },
                    function (isOk, callback) {
                        connection.query('select account from users where uid = ?', [data.sub_uid],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result && result.length > 0) {
                                    callback(null, result[0].account);
                                } else {
                                    callback('查不到该子账号信息');
                                }
                            });
                    }
                ],
                function (err, res) {
                    connection.release();
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, res);
                    }
                })
        });
    }
}

/**
 * 修改入职/离职时间(主账号才可以)
 */
UserDao.setSubJobTime = function (data, cb) {
    if (!data) {
        cb('请求参数不完整');
    } else {

        DBFactory.getConnection(function (error, connection) {
            if (error) {
                cb(error);
                return;
            }
            async.waterfall([
                    function (callback) {
                        var sql = 'update user_subaccount set';
                        var sqlValue = [];
                        if (data.created_date) {
                            sql += ' created_date = ?';
                            sqlValue.push(data.created_date);
                        }
                        if (data.created_date && data.created_date > simpleDateFormat(new Date())) {
                            callback('入职时间不能大于当前时间');
                            return;
                        }
                        if (data.quit_date && data.quit_date > simpleDateFormat(new Date())) {
                            callback('离职时间不能大于当前时间');
                            return;
                        }
                        if (data.hasOwnProperty('quit_date')) {
                            if (sqlValue.length > 0) {
                                sql += ',';
                            }
                            sql += ' quit_date = ?,sub_status = 0';
                            sqlValue.push(data.quit_date);
                        }
                        sql += ' where uid = ? and app_sid = ? and sub_uid = ?';
                        sqlValue.push(data.uid);
                        sqlValue.push(data.app_sid);
                        sqlValue.push(data.sub_uid);
                        connection.query(sql, sqlValue,
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result.affectedRows > 0) {
                                    callback(null, true);
                                } else {
                                    callback('操作失败');
                                }
                            });
                    },
                    function (isOk, callback) {
                        connection.query('select account from users where uid = ?', [data.sub_uid],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result && result.length > 0) {
                                    callback(null, result[0].account);
                                } else {
                                    callback('查不到该子账号信息');
                                }
                            });
                    }
                ],
                function (err, res) {
                    connection.release();
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, res);
                    }
                })
        });
    }
}

/**
 * 删除子账号
 */
UserDao.delSubAccount = function (data, cb) {
    if (!data) {
        cb('请求参数不完整');
    } else {

        DBFactory.getConnection(function (error, connection) {
            if (error) {
                cb(error);
                return;
            }
            async.waterfall([
                    function (callback) {
                        var sql = 'delete from user_subaccount where sub_uid = ? and app_sid = ? and uid = ?';
                        var sqlValue = [data.sub_uid, data.app_sid, data.uid];
                        connection.query(sql, sqlValue,
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result.affectedRows > 0) {
                                    callback(null, true);
                                } else {
                                    callback('删除失败');
                                }
                            });
                    },
                    function (isOk, callback) {
                        connection.query('select account from users where uid = ?', [data.sub_uid],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result && result.length > 0) {
                                    callback(null, result[0].account);
                                } else {
                                    callback('查不到该子账号信息');
                                }
                            });
                    }
                ],
                function (err, res) {
                    connection.release();
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, res);
                    }
                })
        });

    }
}

UserDao.getEasySubInfo = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }
    console.log(data);
    var sql = 'select a.sub_uid,a.sub_name,a.group_name,a.sub_qq,a.sub_wx,a.act_no,a.act_count FROM user_subaccount a where a.uid = ? and a.uid_status = 1 and a.app_sid = ? ';
    var sqlValue = [data.uid, data.app_sid];

    if (data.group_name) {
        sql += ' and group_name = ?';
        sqlValue.push(data.group_name);
    }
    DBFactory.poolQuery(sql, sqlValue,
        function () {
            cb('no connection');
        },
        function (err, result) {
            if (err) {
                cb(err);
                console.log(err);
                return;
            }
            cb(null, result);
        }
    );
}

/**
 * 获取所有子账号信息或所属团队信息
 */
UserDao.getSubInfo = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }
    var subInfo = {};
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([
            // function (callback) {
            //     if (data.is_sub == 0) {
            //         //获取主账号的权限
            //         var sql = 'select c.*,GROUP_CONCAT(distinct d.group_name) group_name from (select a.uid,a.app_sid,GROUP_CONCAT(b.name) vipInfo,GROUP_CONCAT(a.lvl) viplvl from user_vip a LEFT JOIN app_vip b on a.vip_sid = b.sid and a.app_sid = b.app_sid where a.uid = ? and a.end_time > ? ';
            //         var sqlValue = [data.uid, new Date()];
            //         if (data.app_sid) {
            //             sql += ' and a.app_sid = ?';
            //             sqlValue.push(data.app_sid);
            //         } else {
            //             sql += ' group by app_sid';
            //         }
            //         sql += ')c LEFT JOIN user_subaccount d ON c.uid = d.uid and c.app_sid = d.app_sid GROUP BY app_sid';
            //         console.log(sql);
            //         connection.query(sql, sqlValue, function (err, result) {
            //             if (err) {
            //                 callback(err);
            //                 return;
            //             }
            //             result.forEach(function (o) {
            //                 var vipInfo = [];
            //                 if (o.viplvl) {
            //                     for (var i = 0; i < o.viplvl.split(',').length; i++) {
            //                         var vip = {};
            //                         vip.vip_lvl = o.viplvl.split(',')[i];
            //                         vip.vip_name = o.vipInfo.split(',')[i];
            //                         vipInfo.push(vip);
            //                     }
            //                 }
            //                 delete o.viplvl;
            //                 delete o.vipInfo;
            //                 o.vipInfos = vipInfo;
            //             });
            //             callback(null, result);
            //         });
            //     } else {
            //         callback(null, null);
            //     }
            //
            // },
            function (callback) {
                if (data.is_sub == 0) {
                    //获取主账号的uid、app_sid、所有的group_name
                    var sql = 'select uid,app_sid,GROUP_CONCAT(distinct group_name) group_name from user_subaccount where uid = ? ';
                    var sqlValue = [data.uid];
                    if (data.groupMng) {
                        sql += ' and group_name = ?';
                        sqlValue.push(data.groupMng);
                    }
                    if (data.app_sid) {
                        sql += ' and app_sid = ?';
                        sqlValue.push(data.app_sid);
                    } else {
                        sql += ' group by app_sid';
                    }
                    connection.query(sql, sqlValue, function (err, result) {
                        if (err) {
                            callback(err);
                            return;
                        }
                        if (result.length > 0) {
                            subInfo.uidInfo = result[0];
                            if (!data.groupMng) {
                                //获取主账号的vip权限
                                var sql2 = 'select a.lvl,a.vip_sid,b.name,a.vip_type from user_vip a LEFT JOIN app_vip b on a.vip_sid = b.sid and a.app_sid = b.app_sid where a.uid = ? and a.end_time > ? and a.vip_type = 0';
                                var sqlValue2 = [data.uid, new Date()];
                                if (data.app_sid) {
                                    sql2 += ' and a.app_sid = ?';
                                    sqlValue2.push(data.app_sid);
                                } else {
                                    sql2 += ' group by a.app_sid';
                                }
                                connection.query(sql2, sqlValue2, function (e, result2) {
                                    if (e) {
                                        callback(e);
                                        return;
                                    }
                                    subInfo.uidInfo.vipInfos = result2;
                                    callback(null, true);
                                });
                            } else {
                                subInfo.uidInfo.vipInfos = data.vipInfo;
                                callback(null, true);
                            }
                        } else {
                            callback('该主账号没有子账号信息列表');
                        }
                    });
                } else {
                    callback(null, null);
                }

            },
            function (isOK, callback) {
                //还可以添加多少个子账号
                if (subInfo.uidInfo) {
                    var vips = subInfo.uidInfo.vipInfos;
                    if (data.is_sub == 0) {
                        if (!data.groupMng) {
                            var subLvl = 0;
                            if (vips) {
                                for (var i = 0; i < vips.length; i++) {
                                    if (vips[i].name && vips[i].name.indexOf('多操作员') >= 0) {
                                        subLvl = vips[i].lvl;
                                        subInfo.uidInfo.vipInfos.splice(i, 1);
                                    }
                                }
                            }
                        } else {
                            subLvl = data.subLvl;
                        }
                        DBFactory.poolQuery('select count(1) totalNum from user_subaccount where uid = ? ', [data.uid],
                            function () {
                                callback('no connection');
                            },
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result[0]) {
                                    subInfo.leftSubNum = subLvl - result[0].totalNum;
                                    subInfo.AllSubNum = subLvl;
                                    callback(null, true);
                                }
                            }
                        );
                    } else {
                        callback(null, true);
                    }
                } else {
                    callback(null, true);
                }
            },
            //查返回的子账号数量
            function (uid_auth, callback) {
                var sql = '';
                if (data.sub_mc) {
                    sql += 'select count(1) totalNum from(select a.uid,a.sub_uid,a.app_sid FROM user_subaccount a LEFT JOIN users b ON';
                } else {
                    sql += 'select COUNT(1) totalNum FROM user_subaccount a LEFT JOIN users b ON';
                }
                var sqlValue = [];
                //主账号身份
                if (data.is_sub == 0) {
                    sql += ' a.uid = b.uid where a.uid = ?';
                    sqlValue.push(data.uid);
                    if (data.app_sid) {
                        sql += ' and app_sid = ?';
                        sqlValue.push(data.app_sid);
                    }
                    if (data.sub_account) {
                        sql += ' and b.account like ?';
                        sqlValue.push("%" + data.sub_account + "%");
                    }
                    if (data.sub_status) {
                        sql += ' and a.sub_status = ?';
                        sqlValue.push(data.sub_status);
                    }
                    if (data.sub_name) {
                        sql += ' and a.sub_name like ?';
                        sqlValue.push("%" + data.sub_name + "%");
                    }
                    if (data.group_name) {
                        sql += ' and a.group_name like ?';
                        sqlValue.push("%" + data.group_name + "%");
                    }
                    //组长只能查看自己组员的信息
                    if (data.groupMng) {
                        sql += ' and a.group_name = ? and sub_uid != ?';
                        sqlValue.push(data.groupMng);
                        sqlValue.push(data.group_uid);
                    }
                    if (data.sub_qq) {
                        sql += ' and a.sub_qq like ?';
                        sqlValue.push("%" + data.sub_qq + "%");
                    }
                } else {
                    //子账号身份
                    sql += ' a.uid = b.uid where a.sub_uid = ?';
                    sqlValue.push(data.uid);
                    if (data.app_sid) {
                        sql += ' and a.app_sid = ?';
                        sqlValue.push(data.app_sid);
                    }
                    if (data.main_account) {
                        sql += ' and b.account like ?';
                        sqlValue.push("%" + data.main_account + "%");
                    }
                    if (data.sub_status) {
                        sql += ' and a.sub_status = ?';
                        sqlValue.push(data.sub_status);
                    }
                    if (data.main_name) {
                        sql += ' and b.name like ?';
                        sqlValue.push("%" + data.main_name + "%");
                    }
                    if (data.created_date) {
                        sql += ' and date_format(a.created_date,"%Y-%m-%d") = date_format(?,"%Y-%m-%d")';
                        sqlValue.push(data.created_date);
                    }
                }
                if (data.sub_mc) {
                    sql += ')c INNER JOIN (select e.app_sid,e.uid,e.sub_uid,GROUP_CONCAT(f.account,e.sub_name,IFNULL(e.sub_qq,""),IFNULL(e.group_name,"")) sub_content from user_subaccount e LEFT JOIN users f on e.sub_uid = f.uid GROUP BY e.sub_uid,e.uid) d ON d.sub_uid = c.sub_uid and d.uid = c.uid and c.app_sid = d.app_sid and d.sub_content like ?';
                    sqlValue.push('%' + data.sub_mc + '%');
                }
                connection.query(sql, sqlValue, function (err, result) {
                    if (err) {
                        cb(err);
                        console.log(err);
                        return;
                    }
                    if (result.length > 0) {
                        subInfo.totalNum = result[0].totalNum;
                    }
                    callback(null, true);
                });
            },
            //查符合条件的子账号信息
            function (uid_auth, callback) {
                var sql = '';
                if (data.sub_mc) {
                    sql += 'select c.* from(';
                }
                sql += 'select a.*,(DATEDIFF(IFNULL(a.quit_date,?),a.created_date)) days,b.name,b.account from user_subaccount a left join users b';
                var sqlValue = [];
                sqlValue.push(new Date());
                //主账号身份
                if (data.is_sub == 0) {
                    sql += ' on a.sub_uid = b.uid where a.uid = ? ';
                    sqlValue.push(data.uid);
                    if (data.app_sid) {
                        sql += ' and a.app_sid = ?';
                        sqlValue.push(data.app_sid);
                    }
                    if (data.sub_account) {
                        sql += ' and b.account like ?';
                        sqlValue.push("%" + data.sub_account + "%");
                    }
                    if (data.sub_status) {
                        sql += ' and a.sub_status = ?';
                        sqlValue.push(data.sub_status);
                    }
                    if (data.sub_name) {
                        sql += ' and a.sub_name like ?';
                        sqlValue.push("%" + data.sub_name + "%");
                    }
                    if (data.group_name) {
                        sql += ' and a.group_name like ?';
                        sqlValue.push("%" + data.group_name + "%");
                    }
                    //组长只能查看自己组员的信息
                    if (data.groupMng) {
                        sql += ' and a.group_name = ? and sub_uid != ?';
                        sqlValue.push(data.groupMng);
                        sqlValue.push(data.group_uid);
                    }
                    if (data.sub_qq) {
                        sql += ' and a.sub_qq like ?';
                        sqlValue.push("%" + data.sub_qq + "%");
                    }
                    // if (data.created_date) {
                    //     sql += ' and date_format(a.created_date,"%Y-%m-%d") = date_format(?,"%Y-%m-%d")';
                    //     sqlValue.push(data.created_date);
                    // }
                } else {
                    //子账号身份
                    sql += ' on a.uid = b.uid  where a.sub_uid = ? ';
                    sqlValue.push(data.uid);
                    if (data.app_sid) {
                        sql += ' and a.app_sid = ?';
                        sqlValue.push(data.app_sid);
                    }
                    if (data.main_account) {
                        sql += ' and b.account like ?';
                        sqlValue.push("%" + data.main_account + "%");
                    }
                    if (data.sub_status) {
                        sql += ' and a.sub_status = ?';
                        sqlValue.push(data.sub_status);
                    }
                    if (data.main_name) {
                        sql += ' and b.name like ?';
                        sqlValue.push("%" + data.main_name + "%");
                    }
                    if (data.created_date) {
                        sql += ' and date_format(a.created_date,"%Y-%m-%d") = date_format(?,"%Y-%m-%d")';
                        sqlValue.push(data.created_date);
                    }
                }
                if (data.sub_mc) {
                    sql += ')c INNER JOIN (select e.app_sid,e.uid,e.sub_uid,GROUP_CONCAT(f.account,e.sub_name,IFNULL(e.sub_qq,""),IFNULL(e.group_name,"")) sub_content from user_subaccount e LEFT JOIN users f on e.sub_uid = f.uid GROUP BY e.sub_uid,e.uid) d ON d.sub_uid = c.sub_uid and d.uid = c.uid and c.app_sid = d.app_sid and d.sub_content like ?';
                    sqlValue.push('%' + data.sub_mc + '%');
                }
                //排序(单选)
                if (data.sortWord) {
                    sql += ' order by ';
                    if (data.sub_mc) {
                        sql += 'c.';
                    }
                    sql += data.sortWord;
                    if (data.isASC == 1) {
                        sql += ' asc';
                    } else {
                        sql += ' desc';
                    }
                }
                if (data.hasOwnProperty('pageNum') || data.hasOwnProperty('page')) {
                    var pageNum = data.pageNum ? data.pageNum : 10;
                    var page = data.page ? data.page : 1;
                    sql += ' limit ' + (page - 1) * pageNum + ',' + pageNum;
                }
                console.log("sub_acc:" + sql);
                console.log(sqlValue);
                connection.query(sql, sqlValue, function (err, result) {
                    if (err) {
                        cb(err);
                        console.log(err);
                        return;
                    }
                    result.forEach(function (o) {
                        o.created_date = simpleDateFormat(o.created_date);
                        if (o.quit_date) o.quit_date = simpleDateFormat(o.quit_date);
                    });
                    subInfo.Info = result;
                    callback(null, subInfo);
                });
            },
        ], function (err, res) {
            connection.release();
            if (err) {
                cb(err);
            } else {
                cb(null, res);
                return;
            }
        });
    });

}

/**
 * 选择身份
 * @param app_sid、account、password
 */
UserDao.chooseIdentity = function (data, cb) {
    if (!data) {
        cb('请求参数不完整');
    } else {
        DBFactory.getConnection(function (error, connection) {
            if (error) {
                cb(error);
                return;
            }
            async.waterfall([
                    function (callback) {//先查是否有存在子账号
                        //验证用户登录
                        var sql = 'select uid,"主账号" identity,account,name from users where uid = ? and status = 1 limit 1';
                        var sqlValue = [data.uid];
                        connection.query(sql, sqlValue, function (err, result) {
                            if (err) {
                                callback(err);
                                return;
                            }
                            callback(null, result[0]);
                        });
                    },
                    function (user, callback) {//先查是否有存在子账号
                        //验证用户登录
                        var sql = 'select vip_sid,lvl,created_time,end_time,vip_type from user_vip where uid = ? and app_sid = ?';
                        var sqlValue = [data.uid, data.app_sid];
                        connection.query(sql, sqlValue, function (err, result) {
                            if (err) {
                                callback(err);
                                return;
                            }
                            if (result) {
                                result.forEach(function (vip) {
                                    vip.can_use = 1;
                                    if (vip.created_time) vip.created_time = simpleDateFormat(vip.created_time);
                                    if (vip.end_time) vip.end_time = simpleDateFormat(vip.end_time);
                                    if (vip.end_time < simpleDateFormat(new Date())) {
                                        vip.can_use = 0;
                                    }
                                })
                            }
                            user.vipInfo = result;
                            callback(null, user);
                        });
                    },
                    function (users, callback) {
                        //其他主账号身份（如果该主账号被拉黑，就不显示在这里）
                        var sql = 'select a.sub_uid uid,a.uid main_uid,a.sub_name nick,a.group_name group_name,a.uid_status,b.account main_account,b.name main_name from user_subaccount a LEFT JOIN users b  on a.uid = b.uid LEFT JOIN user_app_new_agent c on a.app_sid = c.app_sid and a.uid = c.uid where a.sub_uid = ? and a.sub_status = 1 and b.status = 1  and a.app_sid = ? and c.status = 1';
                        var sqlValue = [data.uid, data.app_sid];
                        connection.query(sql, sqlValue, function (err, result) {
                            if (err) {
                                callback(err);
                                return;
                            }
                            result.push(users);
                            callback(null, result);
                        });
                    }
                ],
                function (err, res) {
                    connection.release();
                    if (err) {
                        cb(err);
                        return;
                    }
                    cb(null, res);
                });

        });
    }
}


//@data: token appSid(可选) uid(可选) startTime(可选) endTime(可选) page(可选) pageNum(可选)
UserDao.moneyDetail = function (data, cb) {

    var sql = 'SELECT uid,original_money,money,app_sid,created_time,comment,sign FROM user_money WHERE uid = ? ';
    var value = [data.uid];

    if (data.appSid) {
        sql += 'AND app_sid = ? ';
        value.push(data.appSid);
    }

    if (data.startTime && data.endTime) {
        data.startTime += ' 00:00:00';
        data.endTime += ' 23:59:59';
        sql += 'and created_time >= ? and created_time <= ? ';
        value.push(data.startTime);
        value.push(data.endTime);
    } else if (data.startTime) {
        var startTime = data.startTime + ' 00:00:00';
        var endTime = data.startTime + ' 23:59:59';
        sql += 'and created_time >= ? and created_time <= ? ';
        value.push(startTime);
        value.push(endTime);
    }

    var pageNum = data.pageNum ? data.pageNum : 10;
    var page = data.page ? data.page : 1;
    sql += 'limit ' + (page - 1) * pageNum + ',' + pageNum;

    DBFactory.poolQuery(sql, value,
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb(err, null);
                return;
            }
            var moneyList = {
                moneyList: result
            }
            cb(null, moneyList);
        });
}

UserDao.accountanduid = function (data, cb) {
    if (!data) {
        cb('请求参数不完整');
        return;
    }
    var sql = '';
    var sqlValue = [];
    if (data.account) {
        sql += 'select account,uid from users where account like ?';
        sqlValue.push('%' + data.account + '%');
    }
    if (data.uid) {
        sql += 'select uid,account from users where uid like ?';
        sqlValue.push('%' + data.uid + '%');
    }
    DBFactory.poolQuery(sql, sqlValue,
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb(err, null);
                return;
            }
            cb(null, result);
        });
}

UserDao.isGroupUid = function (data, cb) {
    if (!data) {
        cb('请求参数不完整');
        return;
    }
    DBFactory.poolQuery('select uid from user_subaccount where group_name = ? and sub_uid = ? and uid = ?', [data.group_name, data.group_uid, data.main_uid],
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb(err);
                return;
            }
            cb(null, result);
        });
}

UserDao.isSubAccountsForTf = function (data, cb) {
    if (!data) {
        cb('请求参数不完整');
        return;
    }

    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
        } else {
            async.waterfall([
                    function (callback) {
                        var sql = 'select uid from users where account = ?';
                        connection.query(sql, [data.new_account],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result && result[0]) {
                                    callback(null, result[0].uid);
                                } else {
                                    callback('不存在此账号');
                                }
                            });
                    },
                    function (new_sub_uid, callback) {
                        var sub_uids = [];
                        if (new_sub_uid != data.main_uid) {
                            sub_uids.push(new_sub_uid);
                        }
                        sub_uids.push(parseInt(data.old_uid));
                        var sql = 'select uid from user_subaccount where uid = ? and sub_uid in (?)';
                        var sqlValue = [data.main_uid, sub_uids];
                        if (data.group_name) {
                            sql += ' and group_name = ?';
                            sqlValue.push(data.group_name);
                        }
                        connection.query(sql, sqlValue
                            , function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result && result.length != 2) {
                                    callback('请确定子账号是否填写有误，或您是否有该权限');
                                } else {
                                    callback(null, new_sub_uid);
                                }
                            });
                    }],
                function (DbErr, info) {
                    connection.release();
                    if (DbErr) {
                        cb(DbErr);
                    } else {
                        cb(null, info);
                    }
                });
        }
    });
}

UserDao.isSubUid = function (data, cb) {
    if (!data) {
        cb('请求参数不完整');
        return;
    }
    data.sub_uids = JSON.parse(data.sub_uids);
    var sql = 'select sub_uid from user_subaccount where sub_uid in (?) and uid = ?';
    var sqlValue = [data.sub_uids, data.main_uid];
    if (data.group_name) {
        sql += ' and group_name = ?';
        sqlValue.push(data.group_name);
    }
    DBFactory.poolQuery(sql, sqlValue,
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb(err);
                return;
            }
            if (result && result.length == data.sub_uids.length) {
                cb(null, result);
            } else {
                cb('有不符合条件的子账号');
            }
        });
}

UserDao.autoLogin = function (userInfo, cb) {
    if (!userInfo) return cb(new Error(500));

    var applist = [];
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
        } else {
            async.waterfall([
                    function (callback) {
                        connection.query('select * from users where account = ? ', [userInfo.account],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result[0]) {
                                    callback(null, result[0]);
                                } else {
                                    callback('不存在此用户');
                                }
                            });
                    },
                    function (user, callback) {
                        userInfo.uid = user.uid;
                        userInfo.name = user.name;
                        userInfo.account = user.account;
                        userInfo.age = user.age == null ? "" : user.age;
                        userInfo.id_card = user.id_card == null ? "" : user.id_card;
                        userInfo.wx_account = user.wx_account == null ? "" : user.wx_account;
                        userInfo.ali_account = user.ali_account == null ? "" : user.ali_account;
                        userInfo.recommendCode = uidToCode(user.uid);
                        userInfo.money = 0;
                        userInfo.real_name = user.real_name;
                        userInfo.secret_pwd = user.secret_pwd ? true : false;
                        userInfo.appInfo = [];

                        UserDao.hasRecommender(userInfo.uid, function (e, result) {
                            if (e) {
                                callback(e);
                            } else {
                                for (var i = 0; i < result.length; i++) {
                                    var recommender = result[i].recommender;
                                    var app_sid = result[i].app_sid;
                                    if (!userInfo.app_sid) userInfo.money += result[i].money;
                                    if (userInfo.app_sid && userInfo.app_sid == app_sid) userInfo.money = result[i].money;
                                    if (applist.indexOf(app_sid) < 0) {
                                        if (userInfo.app_sid && app_sid != userInfo.app_sid) {
                                        } else {
                                            applist.push(app_sid);
                                            var hasRecommender = 0;
                                            if (recommender) {
                                                hasRecommender = 1;
                                            }
                                            if (userInfo.app_sid) {
                                                if (result[i].status == 0) {
                                                    var err = {};
                                                    err.status = '已被禁用';
                                                    err.comment = result[i].comment;
                                                    callback(err);
                                                    return;
                                                }
                                            }
                                            var applists = {
                                                app_sid: app_sid,
                                                reg_time: simpleDateFormat(result[i].created_time),
                                                app_name: result[i].name,
                                                hasRecommender: hasRecommender,
                                                group_name: result[i].group_name,
                                                status: result[i].status,
                                                comment: result[i].comment,
                                                pre_agent_lvl: result[i].pre_agent_lvl,
                                            }
                                            userInfo.appInfo.push(applists);
                                        }
                                    }
                                }
                                callback(null, userInfo);
                            }
                        });
                    },
                    function (userInfo, callback) {
                        //查用户是否有使用过该app，没有就新增user_agent记录
                        if (applist.length == 0 && userInfo.app_sid) {
                            UserDao.addAgent(userInfo, function (e, data) {
                                if (e) {
                                    console.log(e);
                                    callback(e);
                                    return;
                                }
                                if (data) {
                                    var applists = {
                                        app_sid: userInfo.app_sid,
                                        app_name: data.name,
                                        hasRecommender: 0
                                    }
                                    userInfo.appInfo.push(applists);
                                    userInfo.server_time = simpleDateFormat(new Date());
                                }
                                callback(null, userInfo);
                            });
                        } else {
                            //有的话，就获取他的app所属的vip信息
                            UserDao.getVipInfo(userInfo, function (e, data) {
                                if (e) {
                                    callback(e);
                                } else {
                                    //现在没有试用期了
                                    // loginInfo.probation = probation(data.created_time);
                                    if (data) {
                                        for (var i = 0; i < userInfo.appInfo.length; i++) {
                                            var ob = [];
                                            var viplists = {};
                                            for (var j = 0; j < data.length; j++) {
                                                if (data[j].app_sid == applist[i]) {
                                                    userInfo.isEndTime = vipEndTime(data[j].end_time);
                                                    if (userInfo.isEndTime.can_use == 1) {
                                                        // userInfo.recommendCode = uidToCode(userInfo.uid);
                                                    }
                                                    userInfo.isEndTime.vip_end_time = simpleDateFormat(userInfo.isEndTime.vip_end_time);
                                                    var vipInfo = {
                                                        vip_sid: data[j].vip_sid,
                                                        vip_name: data[j].name,
                                                        end_time: userInfo.isEndTime.vip_end_time,
                                                        vip_level: data[j].lvl,
                                                        vip_type: data[j].vip_type,
                                                        can_use: userInfo.isEndTime.can_use
                                                    }
                                                    ob.push(vipInfo);
                                                    delete userInfo.isEndTime;
                                                }
                                            }
                                            ob.forEach(function (o) {
                                                viplists[o.vip_sid] = o;
                                            });
                                            userInfo.appInfo[i].vipInfo = viplists;
                                        }
                                    }
                                    callback(null, userInfo);
                                }
                            });
                        }
                    },
                ],
                function (DbErr, info) {
                    if (DbErr) {
                        cb(DbErr);
                    } else {
                        cb(null, info);
                    }
                }
            );
        }
    });
}


UserDao.bandAccount = function (data, cb) {
    if (!data) return cb(new Error(500));

    var sql = 'UPDATE users SET ';
    var value = [];
    var setSqls = [];
    if (data.ali_account) {
        setSqls.push('ali_account = ? ');
        value.push(data.ali_account);
    }
    if (data.wx_account) {
        setSqls.push('wx_account = ? ');
        value.push(data.wx_account);
    }
    if (data.real_name) {
        setSqls.push('real_name = ? ');
        value.push(data.real_name);
    }
    sql += setSqls.toString() + 'WHERE uid = ? ';
    value.push(data.uid);
    DBFactory.poolQuery(sql, value,
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb(err);
                return;
            }
            cb(null, '修改成功');
        });

}

UserDao.checkRCCode = function (data, cb) {
    if (!data) return cb(new Error(500));

    var sql = 'SELECT * FROM user_app_new_agent WHERE uid = ? AND app_sid = ? ';
    var value = [data.uid, data.app_sid];
    DBFactory.poolQuery(sql, value,
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb(err);
                return;
            }
            var isRight = false;
            if (result && result[0]) {
                isRight = true;
            }
            console.log('result');
            console.log(result);
            console.log(result[0]);
            cb(null, {isRight: isRight});
        });

}

UserDao.getAppkey = function (uid, app_sid, cb) {
    if (!uid) return cb(new Error(500));
    app_sid = (app_sid == 'paodan' || !app_sid) ? 'benliu' : app_sid;
    var sql = 'select appkey from app_appkey where uid = ?  and app_sid = ? ';
    DBFactory.poolQuery(sql, [uid, app_sid],
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb(err);
                return;
            }
            cb(null, result)
        });
}

UserDao.checkExistWxUnionid = function (wx_unionid, cb) {
    var sql = 'select count(*) as count from user_app_wx_rec where wx_unionid = ? ';
    DBFactory.poolQuery(sql, [wx_unionid],
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb(err);
                return;
            }
            result = (result && result[0] && result[0].count > 0) ? true : false;
            cb(null, result);
        });
}